import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.imageio.ImageIO;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.qq.spirit.HttpUtil;
import com.qq.spirit.image.OCR;

public class Test4
{
	static final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
	static
	{
		final DefaultCredentialsProvider credentialsProvider = (DefaultCredentialsProvider) webClient.getCredentialsProvider();
		credentialsProvider.addCredentials("beedoorwei", "959624Xl");
		webClient.setJavaScriptEnabled(false);
		webClient.setCssEnabled(false);
	}

	public static void main(String[] args)
	{
		try
		{
			String code = yazmCode();
			System.out.println(code);
			HtmlPage page = webClient.getPage("http://www.yaowan.com/?m=user&action=login");
			List<HtmlForm> hfList = page.getForms();
			if (!hfList.isEmpty())
			{
				HtmlForm hf = hfList.get(0);
				HtmlSubmitInput button = hf.getInputByName("button");
				HtmlPasswordInput password = hf.getInputByName("password");
				HtmlTextInput username = hf.getInputByName("username");
				HtmlTextInput codeinput = null;
				System.out.println(hf.hasHtmlElementWithId("password"));
				System.out.println(hf.hasHtmlElementWithId("code"));
				if (hf.hasHtmlElementWithId("code"))
				{

					codeinput = hf.getInputByName("code");
				}

				username.setValueAttribute("cyb120");
				password.setValueAttribute("123123");
				if (codeinput != null)
				{
					codeinput.setValueAttribute(code);
				}

				final HtmlPage page2 = button.click();

				System.out.println(page2.asText());
				HtmlAnchor ha = page2.getAnchorByText("双线百零三区");
				System.out.println(ha);
				HtmlPage hp = ha.click();
				System.out.println(hp.asText());
				System.out.println(Arrays.toString(webClient.getCookieManager().getCookies().toArray()));
				Page p = webClient.getPage("http://s103.as.yaowan.com/root/server!getPlayerInfoByUserId.action");
				System.out.println(HttpUtil.decodeResponse(p));
			}
			webClient.closeAllWindows();
		} catch (FailingHttpStatusCodeException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String yazmCode()
	{
		try
		{
			InputStream ins = webClient.getPage("http://www.yaowan.com/Plugins/checkcode.php").getWebResponse().getContentAsStream();
			File f2 = new File(System.currentTimeMillis() + ".jpg");
			createTmpFile(ins, f2);
			File f = pluszy(new FileInputStream(f2));
			String svCode = new OCR().recognizeText(new FileInputStream(f), "jpg");
			System.out.println(f + "\t" + svCode);
			return svCode;
		} catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	public static void createTmpFile(InputStream ins, File f2)
	{
		try
		{
			BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(f2));
			int len = -1;
			byte[] b2 = new byte[1024];
			while ((len = ins.read(b2)) != -1)
			{
				f.write(b2, 0, len);
			}
			f.flush();
			f.close();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static File pluszy(InputStream ins)
	{
		try
		{
			BufferedImage image;
			image = ImageIO.read(ins);
			int width = image.getTileWidth();
			int height = image.getTileHeight();
			Map<Integer, Integer> mapColor = new HashMap<Integer, Integer>();
			for (int i = 0; i < width; i++)
				for (int j = 0; j < height; j++)
				{
					int color = image.getRGB(i, j);
					Integer count = mapColor.get(color);
					if (count == null)
						count = 0;
					count++;
					mapColor.put(color, count);
				}

			List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(mapColor.entrySet());
			Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
			{
				@Override
				public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2)
				{
					return o2.getValue() - o1.getValue();
				}

			});
			int intBack = list.get(0).getKey();
			Set<Integer> setColor = new HashSet<Integer>();
			for (int i = 1; i < 5; i++)
			{
				Map.Entry<Integer, Integer> entry = list.get(i);
				setColor.add(entry.getKey());
			}
			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					int color = image.getRGB(i, j);
					if (setColor.contains(color))
						continue;
					image.setRGB(i, j, intBack);
				}
			}

			File tarFile = new File(System.currentTimeMillis() + ".jpg");
			ImageIO.write(image, "jpg", tarFile);

			return tarFile;

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
